#include <jni.h>
#include <string>
extern "C"{
#include "mm.h"
}
char* getTable(){
    std::string str;
    char*tmp=new char[1024];
    sprintf(tmp,"MEM ADDRESS START AT %p\n",YMM_addr);
    str.append(tmp);
    YMM_map *tmpmap=YMM_fp;

    while (tmpmap!=0){
        sprintf(tmp,"OFFSET:0d%08d\tSIZE:%d",tmpmap->m_addr-YMM_addr,tmpmap->m_size);
        str.append(tmp);
        if(tmpmap==YMM_cp)
            str.append("(cp)");
        str.append("\n");
        tmpmap=tmpmap->nxt;
    };
    return const_cast<char *>(str.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_yricky_memorymanagement_MainActivity_mmInit(JNIEnv *env, jobject thiz,jint size) {
    YMM_init(size);

    return env->NewStringUTF(getTable());
}extern "C"


JNIEXPORT jstring JNICALL
Java_com_yricky_memorymanagement_MainActivity_mmAlloc(JNIEnv *env, jobject thiz, jint size) {
    YMM_alloc(size);
    return env->NewStringUTF(getTable());
}
extern "C"
JNIEXPORT void JNICALL
Java_com_yricky_memorymanagement_MainActivity_mmRelease(JNIEnv *env, jobject thiz) {
    YMM_release();
}extern "C"
JNIEXPORT jstring JNICALL
Java_com_yricky_memorymanagement_MainActivity_mmGetUsage(JNIEnv *env, jobject thiz) {
    std::string str;
    char*tmp=new char[1024];
    sprintf(tmp,"%d,%d",0,YMM_size);
    str.append(tmp);
    YMM_map *tmpmap=YMM_fp;
    while (tmpmap!=0){
        sprintf(tmp,"s%d,%d",tmpmap->m_addr-YMM_addr,tmpmap->m_size);
        str.append(tmp);
        tmpmap=tmpmap->nxt;
    };
    return env->NewStringUTF(str.c_str());
}extern "C"
JNIEXPORT jstring JNICALL
Java_com_yricky_memorymanagement_MainActivity_mmFree(JNIEnv *env, jobject thiz, jint addr_offset,
                                                     jint size) {
    YMM_free(size,YMM_addr+addr_offset);
    return env->NewStringUTF(getTable());
}extern "C"